{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "打开文件出错\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except OSError: #操作系统异常 \n",
    "    print('打开文件出错')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'test.txt'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-7-a2c21fa9f87f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m     \u001b[0mf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'test.txt'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      3\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m     \u001b[0mf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;32mexcept\u001b[0m  \u001b[0mUnicodeDecodeError\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;31m#异常的类型和 except 之后的名称应该相符合\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'test.txt'"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except  UnicodeDecodeError: #异常的类型和 except 之后的名称应该相符合\n",
    "    print('打开文件出错')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数值出错\n",
      "原因是：invalid literal for int() with base 10: 'abc'\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    int(\"abc\")         #只要出错了  后面的语句就不会再被执行\n",
    "except OSError as error:\n",
    "    print('打开文件出错\\n原因是：' + str(error))\n",
    "except TypeError as error:\n",
    "    print('类型出错\\n原因是：' + str(error))\n",
    "except ValueError as error:\n",
    "    print('数值出错\\n原因是：' + str(error))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "#使用多个 except 代码块时，必须坚持对其规范排序，要从最具针对性的异常到最通用的异常\n",
    "dict1 = {'a': 1, 'b': 2, 'v': 22}\n",
    "try:\n",
    "    x = dict1['a']\n",
    "except LookupError:\n",
    "    print('查询错误')\n",
    "except KeyError:\n",
    "    print('键错误')\n",
    "else:\n",
    "    print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "dict1 = {'a': 1, 'b': 2, 'v': 22}\n",
    "try:\n",
    "    x = dict1['a']\n",
    "    print(x)\n",
    "except LookupError:\n",
    "    print('查询错误')\n",
    "except KeyError:\n",
    "    print('键错误')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "出错了！\n",
      "原因是：unsupported operand type(s) for +: 'int' and 'str'\n"
     ]
    }
   ],
   "source": [
    "#一个 except 子句可以同时处理多个异常，这些异常将被放在一个括号里成为一个元组。\n",
    "try:\n",
    "    s = 1 + '1'\n",
    "    int(\"abc\")\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except (OSError, TypeError, ValueError) as error:\n",
    "    print('出错了！\\n原因是：' + str(error))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "try:\n",
    " 检测范围\n",
    "except Exception[as reason]:\n",
    " 出现异常后的处理代码\n",
    "finally:\n",
    " 无论如何都会被执行的代码\n",
    " 如果一个异常在 try 子句里被抛出，而又没有任何的 except 把它截住，那么这个异常会在 finally 子句执行后被抛出。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divide(x, y):\n",
    "    try:\n",
    "        result = x / y\n",
    "        print(\"result is\", result)\n",
    "    except ZeroDivisionError:\n",
    "        print(\"division by zero!\")\n",
    "    finally:\n",
    "        print(\"executing finally clause\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "executing finally clause\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "unsupported operand type(s) for /: 'str' and 'str'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-16-3ad63cdb9b7d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mdivide\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"2\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"1\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m<ipython-input-15-196838ba18f5>\u001b[0m in \u001b[0;36mdivide\u001b[1;34m(x, y)\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mdivide\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m     \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m         \u001b[0mresult\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m/\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      4\u001b[0m         \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"result is\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mresult\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m     \u001b[1;32mexcept\u001b[0m \u001b[0mZeroDivisionError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'str'"
     ]
    }
   ],
   "source": [
    "divide(\"2\", \"1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#else使用情况应该多于finally\n",
    "try:\n",
    " 检测范围\n",
    "except:\n",
    " 出现异常后的处理代码\n",
    "else:\n",
    " 如果没有异常执行这块代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "内容写入文件成功\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    fh = open(\"testfile\", \"w\")\n",
    "    fh.write(\"这是一个测试文件，用于测试异常!!\")\n",
    "except IOError:\n",
    "    print(\"Error: 没有找到文件或读取文件失败\")\n",
    "else:\n",
    "    print(\"内容写入文件成功\")\n",
    "    fh.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "An exception flew by!\n"
     ]
    }
   ],
   "source": [
    "#raise语句抛出一个指定异常\n",
    "try:\n",
    "    raise NameError('HiThere')\n",
    "except NameError:\n",
    "    print('An exception flew by!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "#练习题\n",
    "电脑产生一个零到100之间的随机数字，然后让用户来猜，如果用户猜的数字比这个数字大，提示太大，否则提示太小，当用户正好猜中电脑会提示，\"恭喜你猜到了这个数是......\"。在用户每次猜测之前程序会输出用户是第几次猜\n",
    "测，如果用户输入的根本不是一个数字，程序会告诉用户\"输入无效\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "17\n",
      "第1次猜\n",
      "猜测一个0到100之间的整数200\n",
      "儿子，你咋这么傻，范围在0到100\n",
      "第2次猜\n",
      "猜测一个0到100之间的整数0\n",
      "儿子往大了猜\n",
      "第3次猜\n",
      "猜测一个0到100之间的整数50\n",
      "儿子往小了猜\n",
      "第4次猜\n",
      "猜测一个0到100之间的整数a\n",
      "输入无效\n",
      "第5次猜\n",
      "猜测一个0到100之间的整数17\n",
      "儿子真棒\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "sz = random.randrange(start=0,stop=100)\n",
    "print(sz)\n",
    "count = 0\n",
    "while True: \n",
    "        count+=1\n",
    "        print(\"第\"+str(count)+\"次猜\")\n",
    "        try:\n",
    "            cc = int(input(\"猜测一个0到100之间的整数\"))\n",
    "        except ValueError:\n",
    "            print(\"输入无效\")\n",
    "        else:\n",
    "            if cc>=0 and cc<101:\n",
    "                if cc == sz:\n",
    "                    print(\"儿子真棒\")\n",
    "                    break\n",
    "                elif cc> sz:\n",
    "                    print(\"儿子往小了猜\")\n",
    "                elif cc< sz:\n",
    "                    print(\"儿子往大了猜\")\n",
    "            else:\n",
    "                print(\"儿子，你咋这么傻，范围在0到100\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
